package com.qf.service.impl;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.qf.aop.annocation.OrderDataSource;
import com.qf.consants.RabbitMQConstants;
import com.qf.datasoruce.OrderTableIndexThreadLocal;
import com.qf.entity.Car;
import com.qf.entity.Order;
import com.qf.entity.OrderDetail;
import com.qf.entity.User;
import com.qf.mapper.OrderMapper;
import com.qf.service.IOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Override
    @OrderDataSource // 在调用addOrder方法之前设置数据源
    @Transactional
    public void addOrder(User user, Order order, List<Car> carList) {
        // 2.插入订单
        baseMapper.addOrder(order, OrderTableIndexThreadLocal.get());

        // 插入订单详情
        // 7.封装订单详情
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (Car car : carList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setCount(car.getCount());
            orderDetail.setGprice(car.getGoods().getGprice());
            orderDetail.setGname(car.getGoods().getGname());
            orderDetail.setGdesc(car.getGoods().getGdesc());
            orderDetail.setGid(car.getGoods().getId());
            orderDetail.setOid(order.getId());
            orderDetail.setSum(car.getGoods().getGprice().multiply(BigDecimal.valueOf(car.getCount())));
            orderDetailList.add(orderDetail);
        }

        // 8 从插入订单详情
        baseMapper.batchOrderDetail(orderDetailList, OrderTableIndexThreadLocal.get());
    }

    @Override
    public Order getOrderById(String oid, Integer userIdSuf) {

        Integer dbIndex = (userIdSuf % RabbitMQConstants.ORDER_DB_SIZE) + 1;

        Integer tabIndex = ((userIdSuf / RabbitMQConstants.ORDER_DB_SIZE )% RabbitMQConstants.ORDER_TABLE_SIZE) + 1;

        // 设置数据源
        DynamicDataSourceContextHolder.push("order-"+dbIndex);

        // 根据订单id查询数据
        return baseMapper.getOrderById(oid,tabIndex);
    }

    @Override
    public void updateOrderStatus(Integer userIdSuf, String oid, Integer status) {

        Integer dbIndex = (userIdSuf % RabbitMQConstants.ORDER_DB_SIZE) + 1;

        Integer tabIndex = ((userIdSuf / RabbitMQConstants.ORDER_DB_SIZE )% RabbitMQConstants.ORDER_TABLE_SIZE) + 1;

        // 设置数据源
        DynamicDataSourceContextHolder.push("order-"+dbIndex);

        baseMapper.updateOrderStatus(oid,status,tabIndex);
    }

    @OrderDataSource
    public List<Order> getOrderList(User user) {
        return null;
    }

    @OrderDataSource
    public void updateOrder(User user, String oid, Integer status) {

    }
}
